package boboUtil;

import java.io.Serializable;
import java.util.Objects;

public class BoboHashMap<K,V> extends BoboAbstractMap<K,V>
        implements BoboMap<K,V>, Serializable {


    /*类的静态成员变量*/

    //序列号
    private static final long serialVersionUID = 362498820763181265L;
    //默认初始容量为16.必须是2的幂
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    //最大容量：2^30
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //默认负载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 当桶(bucket)上的结点数大于这个值时会转成红黑树
    static final int TREEIFY_THRESHOLD = 8;
    // 当桶(bucket)上的结点数小于这个值时树转链表
    static final int UNTREEIFY_THRESHOLD = 6;
    // 桶中结构转化为红黑树对应的table的最小大小
    static final int MIN_TREEIFY_CAPACITY = 64;

    /*普通成员变量*/

    // 存储元素的数组，大小总是2的幂次倍
    transient Node<K,V>[] table;

    transient BoboSet<BoboMap.Entry<K,V>> entrySet;
    //元素的个数
    transient int size;
    //修改次数
    transient int modCount;
    //临界值 = 容量*负载因子
    transient int threshold;
    //负载因子
    final float loadFactor;

    /*构造函数*/

    //指定初始容量和负载因子
    public BoboHashMap(int initialCapacity, float loadFactor){
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                    initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                    loadFactor);

        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }
    //指定默认容量
    public BoboHashMap(int initialCapacity){
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    //无参构造函数
    public BoboHashMap(){
        this.loadFactor = DEFAULT_LOAD_FACTOR;
    }
    //返回大于等于cap的最小的二次幂数值。利用位运算：循环右移和按位或
    private int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;

        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    //静态内部类： 链表结点Node
    static class Node<K,V> implements BoboMap.Entry<K,V>{
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        public Node(int hash, K key, V value, Node<K, V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        @Override
        public final K getKey() {
            return key;
        }

        @Override
        public final V getValue() {
            return value;
        }

        @Override
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o){
            if (o == this){
                return true;
            }
            if (o instanceof BoboMap.Entry){
                BoboMap.Entry<?,?> e = (Entry<?,?>) o;
                if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }

    }


    public V put(K key, V value){
        return putVal(hash(key), key, value, false, true);
    }

    //计算key的hash值，用以定位
    static final int hash(Object key){
        int h;
        // h = key.hashCode() 为第一步 取hashCode值
        // h ^ (h >>> 16)  为第二步 高位参与运算
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> p;
        int n,i;

        //table为空时需要扩容
        if ((tab = table) == null || (n = tab.length) == 0){
            n = (tab = resize()).length;
        }

        //计算index，并对null做处理
        if ((p = tab[i = (n-1) & hash]) == null){
            tab[i] = newNode(hash, key, value, null);
        }

        return null;
    }

    Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
    }

    //扩容
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0){
            // 超过最大值就不再扩充了，就只好随你碰撞去吧
            if (oldCap >= MAXIMUM_CAPACITY){
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY){
                newThr = oldThr << 1;
            }
        }
        else if (oldThr > 0){
            newCap = oldThr;
        }
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);
        }

        threshold = newThr;

        Node<K,V>[] newTab = (Node<K,V>[]) new Node[newCap];
        table = newTab;

        if (oldTab != null){
            // 把每个bucket都移动到新的buckets中
            for (int j=0; j<oldCap; j++){
                Node<K,V> e;
                if ((e = oldTab[j]) != null){
                    oldTab[j] = null;
                    if (e.next == null){
                        newTab[e.hash & (newCap-1)] = e;
                    } else if (e instanceof TreeNode){

                    } else {
                        // 链表优化重hash的代码块
                    }
                }
            }
        }

        return newTab;
    }

    //静态内部类：红黑树结点TreeNode
    static final class TreeNode<K,V> extends BoboLinkedHashMap.Entry<K,V>{
        TreeNode<K,V> parent;
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;
        boolean red;

        public TreeNode(int hash, K key, V value, Node<K, V> next) {
            super(hash, key, value, next);
        }
    }

    public int size(){
        return size;
    }

    public boolean isEmpty(){
        return size == 0;
    }
    @Override
    public BoboSet<Entry<K, V>> entrySet() {
        return null;
    }
}
